package com.engine.cn.juc;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 三个线程按照顺序轮流打印ABC,每个线程打印10次
 */
public class OrderedUnlockThread {
    //打印次数，总数是30
    private static final int PRINT_TIMES = 30;
    private static final AtomicInteger COUNTER = new AtomicInteger(0);

    private static void print(char ch, int target) {
        while (COUNTER.get() < PRINT_TIMES) {
            //这一句是实现的精髓
            if (COUNTER.get() % 3 == target) {
                System.out.println(ch);
                COUNTER.incrementAndGet();
            }
            // 避免忙等待（可加短暂休眠）
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        Thread h1 = new Thread(() -> print('A', 0));
        Thread h2 = new Thread(() -> print('B', 1));
        Thread h3 = new Thread(() -> print('C', 2));
        h1.start();
        h2.start();
        h3.start();
    }
}
